from openpyxl import workbook
import os
import time
from xml.dom import minidom
from coordinates_converter import Converter, CRS_Builder, Bursa_Params_Builder


class ExportXLSX:
    def __init__(self) -> None:
        pass

    def createXLSX(self, output_dir, opt_dir, gcp_file, pos_file, img_file):
        xlsx = workbook.Workbook()
        xlsx.remove(xlsx["Sheet"])
        # sheet
        photogroups = xlsx.create_sheet("Photogroups")
        photos = xlsx.create_sheet("Photos")
        controlPoints = xlsx.create_sheet("ControlPoints")
        options = xlsx.create_sheet("Options")

        # 处理photogroups分页
        self.__fill_photogroups(photogroups, opt_dir)
        # 处理photos分页
        self.__fill_photos(photos, pos_file, img_file)
        # 处理控制点分页
        self.__fill_controlPoints(controlPoints, gcp_file)
        # 处理options分页
        self.__fill_options(options)
        # 写入硬盘
        timestamp = time.strftime("%Y_%m_%d_%H_%M", time.localtime())
        output_file_path = os.path.join(
            output_dir, "Block_Import_File" + timestamp + ".xlsx"
        ).replace("\\", "/")
        xlsx.save(output_file_path)

    def __fill_photogroups(self, sheet, opt_dir):
        content = []
        title = [
            "Name",
            "Width",
            "Height",
            "FocalLength",
            "SensorSize",
            "PrincipalPointXmm",
            "PrincipalPointYmm",
            "CameraOrientation",
            "k1",
            "k2",
            "k3",
            "p1",
            "p2",
        ]
        for root, dirs, files in os.walk(opt_dir):
            for file in files:
                opt_file = os.path.join(root, file).replace("\\", "/")
                dom = minidom.parse(opt_file)

                Name = file.split(".")[0]
                Width = dom.getElementsByTagName("Width")[0].firstChild.data
                Height = dom.getElementsByTagName("Height")[0].firstChild.data
                FocalLength = dom.getElementsByTagName("FocalLength")[0].firstChild.data
                SensorSize = dom.getElementsByTagName("FocalLength")[0].firstChild.data
                PrincipalPointXmm = dom.getElementsByTagName("X")[0].firstChild.data
                PrincipalPointYmm = dom.getElementsByTagName("Y")[0].firstChild.data
                CameraOrientation = "XRightYDown"
                k1 = dom.getElementsByTagName("K1")[0].firstChild.data
                k2 = dom.getElementsByTagName("K2")[0].firstChild.data
                k3 = dom.getElementsByTagName("K3")[0].firstChild.data
                p1 = dom.getElementsByTagName("P1")[0].firstChild.data
                p2 = dom.getElementsByTagName("P2")[0].firstChild.data

                content.append(
                    [
                        Name,
                        Width,
                        Height,
                        FocalLength,
                        SensorSize,
                        PrincipalPointXmm,
                        PrincipalPointYmm,
                        CameraOrientation,
                        k1,
                        k2,
                        k3,
                        p1,
                        p2,
                    ]
                )

        for index, value in enumerate(title):
            sheet.cell(row=1, column=index + 1, value=value)

        for index_row, dict in enumerate(content):
            for index_columns, value in enumerate(dict):
                sheet.cell(row=index_row + 2, column=index_columns + 1, value=value)

    def __fill_options(self, sheet):
        sheet.cell(row=1, column=1, value="OptionName")
        sheet.cell(row=1, column=2, value="Value")
        sheet.cell(row=2, column=1, value="SRS")
        sheet.cell(row=2, column=2, value="EPSG:4549")
        sheet.cell(row=3, column=1, value="InRadians")
        sheet.cell(row=3, column=2, value="FALSE")

    def __fill_controlPoints(self, sheet, gcp_file):
        with open(gcp_file) as f:
            lines = f.readlines()
        f.close()

        gcp_list = []
        title = ["Name", "Easting", "Northing", "Height"]
        for line in lines:
            linelist = line.replace(",,", ",").replace("\n", "").split(",")
            gcp_list.append(linelist)

        for index, value in enumerate(title):
            sheet.cell(row=1, column=index + 1, value=value)

        for row_index, row in enumerate(gcp_list):
            for column_index, value in enumerate(row):
                sheet.cell(row=row_index + 2, column=column_index + 1, value=value)

    def __fill_photos(self, sheet, pos_file, img_file):
        with open(pos_file) as f:
            lines = f.readlines()
        f.close()

        coordinate_list = []
        for line in lines:
            line_list = line.replace("\n", "").replace(" ", ",").split(",")
            coordinate_list.append(
                [line_list[0], line_list[1], line_list[2], line_list[3]]
            )
        WGS84 = CRS_Builder.WGS84
        CGCS2000 = CRS_Builder.CGCS2000
        PARAMS7 = Bursa_Params_Builder.WGS84_CGCS2000
        coordinate_list_afterCVT = []
        for list in coordinate_list:
            serial_number = list[0]
            logitude = float(list[2])
            latitude = float(list[1])
            height = float(list[3])
            cvt = Converter()
            x, y, z = (
                cvt.coord([logitude, latitude, height])
                .geodetic_spatialRectangular(WGS84)
                .bursa7params_converte(PARAMS7)
                .spatialRectangular_geodetic(CGCS2000)
                .positive_gaussain_projecton(CGCS2000)
                .export_Coordinate([4, 4, 4])
            )
            coordinate_list_afterCVT.append([serial_number, y, x, z])
        img_coord_list = []
        for postion in coordinate_list_afterCVT:
            a_path = os.path.join(
                img_file, "A", "A" + postion[0].rjust(4, "0") + ".JPG"
            ).replace("\\", "/")
            d_path = os.path.join(
                img_file, "D", "D" + postion[0].rjust(4, "0") + ".JPG"
            ).replace("\\", "/")
            s_path = os.path.join(
                img_file, "S", "S" + postion[0].rjust(4, "0") + ".JPG"
            ).replace("\\", "/")
            w_path = os.path.join(
                img_file, "W", "W" + postion[0].rjust(4, "0") + ".JPG"
            ).replace("\\", "/")
            x_path = os.path.join(
                img_file, "S", "S" + postion[0].rjust(4, "0") + ".JPG"
            ).replace("\\", "/")
            img_coord_list.append([a_path, "A", postion[1], postion[2], postion[3]])
            img_coord_list.append([d_path, "D", postion[1], postion[2], postion[3]])
            img_coord_list.append([s_path, "S", postion[1], postion[2], postion[3]])
            img_coord_list.append([w_path, "W", postion[1], postion[2], postion[3]])
            img_coord_list.append([x_path, "X", postion[1], postion[2], postion[3]])
        title_list = ["Name", "PhotogroupName", "Easting", "Northing", "Height"]

        for index, title in enumerate(title_list):
            sheet.cell(row=1, column=index + 1, value=title)

        for row_index, row in enumerate(img_coord_list):
            for col_index, value in enumerate(row):
                sheet.cell(row=row_index + 2, column=col_index + 1, value=value)


def main():
    e = ExportXLSX()
    pos_file = "D:/arcgisDatasource/test/pos_12_30_15_15_47.txt"
    output_dir = "D:/arcgisDatasource/test"
    img_file = "D:/arcgisDatasource/test"
    opt_dir = "D:/arcgisDatasource/test/optimize_pramas_2021_11_29"
    gcp_file = "D:/arcgisDatasource/test/xk.txt"
    e.createXLSX(
        output_dir=output_dir,
        opt_dir=opt_dir,
        gcp_file=gcp_file,
        pos_file=pos_file,
        img_file=img_file,
    )


if __name__ == "__main__":
    main()
